#!/usr/bin/env node

/**
 * 扩展打包脚本
 * 将构建产物打包成 Chrome 扩展安装包
 */

const fs = require('fs-extra');
const path = require('path');
const archiver = require('archiver');
const chalk = require('chalk');

class ExtensionPackager {
  constructor() {
    this.buildDir = path.resolve(__dirname, '../build');
    this.distDir = path.resolve(__dirname, '../dist');
    this.packageName = 'vhall-stream-saver';
  }

  async package() {
    console.log(chalk.blue('📦 开始打包 Chrome 扩展...'));

    try {
      // 检查构建目录
      await this.checkBuildDirectory();

      // 创建分发目录
      await this.createDistDirectory();

      // 读取版本信息
      const version = await this.getVersion();

      // 创建 ZIP 包
      await this.createZipPackage(version);

      console.log(chalk.green('✅ 打包完成!'));

    } catch (error) {
      console.error(chalk.red('❌ 打包失败:'), error.message);
      process.exit(1);
    }
  }

  async checkBuildDirectory() {
    if (!(await fs.pathExists(this.buildDir))) {
      throw new Error('构建目录不存在，请先运行 npm run build');
    }

    const manifestPath = path.join(this.buildDir, 'manifest.json');
    if (!(await fs.pathExists(manifestPath))) {
      throw new Error('manifest.json 不存在，请检查构建产物');
    }

    console.log(chalk.gray('  ✓ 构建目录检查通过'));
  }

  async createDistDirectory() {
    await fs.ensureDir(this.distDir);
    console.log(chalk.gray('  ✓ 创建分发目录'));
  }

  async getVersion() {
    const manifestPath = path.join(this.buildDir, 'manifest.json');
    const manifest = await fs.readJson(manifestPath);
    return manifest.version || '1.0.0';
  }

  async createZipPackage(version) {
    const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
    const zipFileName = `${this.packageName}-v${version}-${timestamp}.zip`;
    const zipFilePath = path.join(this.distDir, zipFileName);

    console.log(chalk.yellow(`📦 创建 ZIP 包: ${zipFileName}`));

    return new Promise((resolve, reject) => {
      const output = fs.createWriteStream(zipFilePath);
      const archive = archiver('zip', {
        zlib: { level: 9 } // 最高压缩级别
      });

      output.on('close', () => {
        const sizeInMB = (archive.pointer() / 1024 / 1024).toFixed(2);
        console.log(chalk.green(`  ✓ ZIP 包创建完成: ${zipFileName} (${sizeInMB} MB)`));
        console.log(chalk.cyan(`  📁 输出路径: ${zipFilePath}`));
        resolve();
      });

      archive.on('error', (err) => {
        reject(err);
      });

      archive.pipe(output);

      // 添加构建目录中的所有文件
      archive.directory(this.buildDir, false);

      archive.finalize();
    });
  }
}

// 运行打包
if (require.main === module) {
  const packager = new ExtensionPackager();
  packager.package().catch(console.error);
}

module.exports = ExtensionPackager;
